<?php

//Must do: check times login
//Test https....
//CSRF
//Draw workflow....
class Index extends Admin_Controller {

    public function __construct() {
        parent::__construct();
        $this->_load();
    }

    public function index() {
        $this->_replacePhrase();
    }

    public function add() {
        if (!(bool) $this->input->is_ajax_request()) {
            redirect('product/admincp/index');
            return false;
        }

//        $aConfig = $this->_getRuleProduct();
//        $this->load->library('form_validation', null, 'validation');
//        $this->validation->set_rules($aConfig);
//        $this->validation->set_error_delimiters('<div class="error">', '</div>');
//
//        if ($this->validation->run() === false) {
//            $this->return_fail_json($this->_getValidationError());
//            return false;
//        }

        if ((bool) $aCateogry = $this->input->post('category')) {
            if ((bool) $aReturn = $this->category->add($aCateogry)) {
                $this->return_success_json($aReturn, $this->lang->line("phrase var='category.add_new_category_successfully'"));
                return true;
            }
        }
    }

    public function uploadImage() {
        $aConfig = array(
            'encrypt_name' => true,
            'upload_path' => APPPATH . 'static/images/product/',
            'allowed_types' => 'jpeg|jpg|png|bmp',
        );

        $this->load->library('upload', $aConfig);

        if ($this->upload->do_upload('product_image')) {
            if ((bool) $aData = $this->upload->data()) {
                $aImage = $this->product->addImage($aData['file_name']);
                $aConfigImage = array(
                    'source_image' => APPPATH . 'static/images/product/' . $aData['file_name'],
                    //'create_thumb' => TRUE,
                    'maintain_ratio' => TRUE,
                    'width' => 150,
                    'height' => 150,
                    'new_image' => APPPATH . 'static/images/product/thumb/' . $aData['file_name']
                );

                $this->load->library('image_lib', $aConfigImage);

                if ($this->image_lib->resize()) {
                    ///Create obsolute_path_new_image to get link to file image for showing after finish upload
                    //Reason: relative path image, when append image, it not show.
                    $aData += array('obsolute_path_new_image' => base_url() . '/' . $aConfigImage['new_image']);
                    return $this->return_success_json($aConfigImage + $aData, '');
                }

                return $this->return_fail_json($config, $this->image_lib->display_errors('<div class="error">', '</div>'));
            }
        }

        return $this->return_fail_json($aConfig, $this->upload->display_errors('<div class="error">', '</div>'));
    }
    
    public function getList($offset = null) {
        if (!(bool) $this->input->is_ajax_request()) {
            $this->_redirect_index();
        }

        $offset = !empty($offset) ? $offset : 1;
        $aSearch = $this->input->post('search');
        $aProduct = $this->product->getListAdmin($offset, $aSearch);

        //Get list of page.
        $aPage = $this->product->get_pager('product/admincp/index/getList');
        
        $aReturn = array(
            'products' => $aProduct,
            'pages'    => $aPage
        );
        
        $this->return_success_json($aReturn, '');
    }

    public function delete() {
        if (!(bool) $this->input->is_ajax_request()) {
            $this->_redirect_index();
        }

        $aIds = $this->input->post('product_ids');
        $iCurPage = $this->input->post('cur_page');
        $aIds = (array) json_decode($aIds);

        if ((bool) $this->product->delete($aIds)) {
            $aResult = $this->product->getListAdmin((int) $iCurPage);
            //Prepare in case if delete all items in a page.
            if (!empty($aResult)) {
                $this->return_success_json(array('page' => $iCurPage), '');
            } else {
                $this->return_success_json(array('page' => $iCurPage - 1), '');
            }
            return true;
        }

        $this->return_fail_json(NULL, '');
    }

    public function get() {
        if (!(bool) $this->input->is_ajax_request()) {
            $this->_redirect_index();
        }

        $iId = $this->input->post('product_id');

        if ((bool) $oProduct = $this->product->getById($iId, false)) {
            $this->return_success_json($oProduct, '');

            return true;
        }

        $this->return_fail_json(NULL, '');
    }

    public function edit() {
        if (!(bool) $this->input->is_ajax_request()) {
            redirect('product/admincp/index');
            return false;
        }

        $aConfig = $this->_getRuleProduct();
        $this->load->library('form_validation', null, 'validation');
        $this->validation->set_rules($aConfig);
        $this->validation->set_error_delimiters('<div class="error">', '</div>');

        if ($this->validation->run() === false) {
            $this->return_fail_json($this->_getValidationError());

            return false;
        }

        if ((bool) $aProduct = $this->input->post('product')) {
            //Get current page. Use when reload page current after edit.
            $iCurPage = $aProduct['cur_page'];
//            $iCurPage = $aProduct['cur_page'];
            if ((bool) $aProduct = $this->product->edit($aProduct)) {
                $aProduct['cur_page'] = $iCurPage;
                $this->return_success_json($aProduct, $this->lang->line("phrase var='product.edit_product_successfully'"));
                return true;
            }
        }

        return false;
    }

    public function sort() {
        if (!(bool) $this->input->is_ajax_request()) {
            $this->_redirect_index();
        }

        $aColum = $this->input->post('column');
        $sTypeSort = $this->product->sort($aColum);
        $this->return_success_json(array('type_sort' => $sTypeSort), '');
    }

    public function getSort() {
        $this->_sort = $this->session->userdata($this->config->item('sort'));

        if (!(bool) $this->_sort) {
            return array('order' => 'asc');
        }
    }
    
    private function _load() {
        $this->load->library('pagination');
        $this->load->helper(array('url', 'form'));
        $this->load->model(array('user', 'category'));
        $this->lang->load('admin/general', $this->_slang_name);
        $this->lang->load('admin/category', $this->_slang_name);
    }

    private function _replacePhrase() {
        $this->_adata['token'] = (object) array("name" => $this->security->get_csrf_token_name(), "value" => $this->security->get_csrf_hash());
        $this->_adata['phrase_js'] = json_encode($this->lang->language);
        $this->fill_phrase('index', $this->_adata, $this->lang->language);
    }

    private function _getRuleProduct() {
        return array(
            array(
                'field' => 'product[name]',
                'label' => $this->lang->line("pharse var='product.name_product'"),
                'rules' => 'trim|required|min_length[5]'
            ),
            array(
                'field' => 'product[order]',
                'label' => $this->lang->line("pharse var='product.order'"),
                'rules' => 'trim|numeric|greater_than[0]'
            ),
            array(
                'field' => 'product[source]',
                'label' => $this->lang->line("pharse var='product.source'"),
                'rules' => 'trim|required|regex_match[#^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?(\/)?#i]'
            ),
            array(
                'field' => 'product[level]',
                'label' => $this->lang->line("pharse var='product.level'"),
                'rules' => 'trim|required|numeric|greater_than[0]|less_than[4]'
            ),
            array(
                'field' => 'product[language]',
                'label' => $this->lang->line("pharse var='product.language'"),
                'rules' => 'trim|required|numeric|greater_than[0]|less_than[3]'
            ),
            array(
                'field' => 'product[image]',
                'label' => $this->lang->line("pharse var='product.image'"),
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'product[is_actived]',
                'label' => $this->lang->line("pharse var='product.status'"),
                'rules' => 'trim|required|numeric|greater_than[-1]|less_than[2]'
            ),
            array(
                'field' => 'product[is_featured]',
                'label' => $this->lang->line("pharse var='product.featured'"),
                'rules' => 'trim|required|numeric|greater_than[-1]|less_than[2]'
            ),
            array(
                'field' => 'product[summary]',
                'label' => $this->lang->line("pharse var='product.summary'"),
                'rules' => 'trim|required|min_length[20]'
            ),
            array(
                'field' => 'product[description]',
                'label' => $this->lang->line("pharse var='product.description'"),
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'product[meta_title]',
                'label' => $this->lang->line("pharse var='product.meta_title'"),
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'product[meta_keyword]',
                'label' => $this->lang->line("pharse var='product.meta_keyword'"),
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'product[meta_description]',
                'label' => $this->lang->line("pharse var='product.meta_description'"),
                'rules' => 'trim|required'
            ),
            array(
                'field' => 'product[meta_robot]',
                'label' => $this->lang->line("pharse var='product.meta_robot'"),
                'rules' => 'trim|required'
            )
        );
    }

    private function _getValidationError() {
        $aField = array('name', 'order', 'level', 'language', 'status',
            'featured', 'notify', 'description', 'summary', 'meta_title', 'meta_keyword',
            'meta_description', 'meta_robot', 'image', 'source');
        $aValidationError = array();

        foreach ($aField as $field) {
            $aValidationError = array_merge($aValidationError, array("{$field}" => form_error("product[{$field}]")));
        }

        return $aValidationError;
    }
}
?>